namespace ScrumSprintMonitor.UI.Wpf
{
	#region #using Directives

	using System;
	using System.Collections.Generic;
	using System.Windows;
	using System.Windows.Media;
	using System.Windows.Media.Animation;
	using System.Windows.Threading;

	#endregion

	internal class AnimatedPanelHelper
	{
		public static void ArrangeChild(UIElement panel, UIElement element, Rect finalRect, Duration duration)
		{
			var trans = element.RenderTransform as TranslateTransform;
			// create new Translate Transform
			if (trans == null)
			{
				trans = new TranslateTransform();
				element.RenderTransform = trans;
			}

			// tell the child element to arrange itself
			element.Arrange(new Rect(finalRect.Size));

			// keep translation point and store it in its Tag property for rendering later.
			var translatePosition = finalRect.TopLeft;

			panel.Dispatcher.BeginInvoke(new Action<FrameworkElement, KeyValuePair<Point, Duration>>(BeginAnimation), DispatcherPriority.Render, element,
			                             new KeyValuePair<Point, Duration>(translatePosition, duration));
		}

		private static void BeginAnimation(FrameworkElement element, KeyValuePair<Point, Duration> translatePositionAndDuration)
		{
			var xKeyFrame = new SplineDoubleKeyFrame
			                	{
			                		KeyTime = KeyTime.FromPercent(1.0),
			                		Value = translatePositionAndDuration.Key.X
			                	};
			var yKeyFrame = new SplineDoubleKeyFrame
			                	{
			                		KeyTime = KeyTime.FromPercent(1.0),
			                		Value = translatePositionAndDuration.Key.Y
			                	};
			var animationX = new DoubleAnimationUsingKeyFrames
			                 	{
			                 		Duration = translatePositionAndDuration.Value,
			                 		AccelerationRatio = 0.5,
			                 		DecelerationRatio = 0.5,
			                 		KeyFrames = new DoubleKeyFrameCollection
			                 		            	{
			                 		            		xKeyFrame,
			                 		            		xKeyFrame
			                 		            	}
			                 	};
			var animationY = new DoubleAnimationUsingKeyFrames
			                 	{
			                 		Duration = translatePositionAndDuration.Value,
			                 		AccelerationRatio = 0.5,
			                 		DecelerationRatio = 0.5,
			                 		KeyFrames = new DoubleKeyFrameCollection
			                 		            	{
			                 		            		yKeyFrame,
			                 		            		yKeyFrame
			                 		            	}
			                 	};

			// hook up X and Y translate transformations
			element.RenderTransform.BeginAnimation(TranslateTransform.XProperty, animationX, HandoffBehavior.Compose);
			element.RenderTransform.BeginAnimation(TranslateTransform.YProperty, animationY, HandoffBehavior.Compose);
		}
	}
}